package com.hykj.coca.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 密钥管理
 */
public class SecretKeyManager {

    public static final String tlsPrivStr;
    public static final String tlsPubStr;
    public static final String alipayPrivStr;
    public static final String alipayPubStr;

    static {
        tlsPrivStr = read("tls_private_key");
        tlsPubStr = read("tls_public_key");
        alipayPrivStr = read("alipay_private_key");
        alipayPubStr = read("alipay_public_key");
    }

    private static String read(String filename) {
        Resource resource = new ClassPathResource(filename);
        if (resource.exists()) {
            BufferedInputStream inputStream = null;
            ByteArrayOutputStream outputStream = null;
            try {
                inputStream = new BufferedInputStream(resource.getInputStream());
                outputStream = new ByteArrayOutputStream(512);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }

                return new String(outputStream.toByteArray(), "UTF-8");

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";
    }
}
